package edu.pdx.cs.cs542s07.minichess;

import java.io.IOException;

public class MiniChess {
	
	private static Board board;
	private static BoardController controller;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		try {
			playNormalGame();
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}

	}
	
	
	private static void playAutomatedGame() {
		board = new Board();
		controller = new BoardController();
		ScoreFactory fac = new ScoreFactory();
		
		System.out.println("Welcome to MiniChess!");
		System.out.print(board);
		System.out.println("Score: " + board.getScore());
		System.out.println();
		while(!board.isGameOver()) {
			makeNegamaxMove();
			if (board.isResigned()) {
				System.out.println("Player has resigned.");
			} else {
				System.out.print(board);
				System.out.println("Score: " + board.getScore());
				System.out.println();
			}
		}

		
	}
	
	private static void playNormalGame() 
	throws IOException, IllegalMoveException  {
		
		board = new Board();
		controller = new BoardController();
		ScoreFactory fac = new ScoreFactory();
		
		
		System.out.println("Welcome to MiniChess!");
		System.out.println("Enter 'q' to quit.");
		System.out.println(board);
		System.out.println("Score: " + board.getScore());
		
		while(!board.isGameOver()) {
			makeHumanMove();
			System.out.println(board);
			System.out.println("Score: " + board.getScore());
			if (!board.isGameOver()) {
				//makeRandomMove();
				makeNegamaxMove();
				System.out.println(board);
				System.out.println("Score: " + board.getScore());
				if (board.isGameOver()) {
					System.out.println("You lose! :(");
				}
			} else {
				if (board.isResigned()) {
					System.out.println("Opponent has resigned.");
				}
				System.out.println("You win!!");
			}
			
			
			
			
		}
		
	}
	
	private static String getHumanMoveString() 
	throws IOException {
		StringBuffer buff = new StringBuffer();
		System.out.println("Enter a move:");
		char c = 0;
		while(c != '\n' && c != -1) {
			c = (char)System.in.read();
			if (c > 0) {
				buff.append(c);
			}
			if (c == 'q' || c == 'Q') {
				// quit game
				System.out.println("Quitting. Bye!");
				System.exit(0);
			}
		}
		return buff.toString();
	}
	
	private static void makeHumanMove()
	throws IOException {
		
		// keep trying to get a legit move until you succeed.
		boolean moveMade = false;
		while(!moveMade) {
			String s = getHumanMoveString();
			try {
				controller.humanMove(s, board);
				moveMade = true;
			} catch (IllegalMoveException e) {
				System.out.println(e.getMessage());
				System.out.println("Try again.");
			} 
		}
		
		
	}
	
	private static void makeRandomMove() {
		//controller.randomMove(board);
		controller.randomImmediateBestMove(board);
	}
	
	private static void makeNegamaxMove() {
		controller.negamaxBestMove(board);
	}



}
